/**
 * 
 */
package ua.at.tsvetkov.samizdat.adapters;

import ua.at.tsvetkov.application.ActivityStack;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.data.DataLoadedAuthors;
import ua.at.tsvetkov.samizdat.data.FavoriteAuthors;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * D@author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AdtLoadedAuthors extends BaseAdapter {

	private LayoutInflater		mInflater;
	private Activity				context;
	private FavoriteAuthors		favoriteAuthors;
	private DataLoadedAuthors	dataLoadedAuthors;

	public AdtLoadedAuthors(DataLoadedAuthors dataLoadedAuthors) {
		this.dataLoadedAuthors = dataLoadedAuthors;
		this.context = ActivityStack.getLastActivity();
		this.mInflater = LayoutInflater.from(context);
		favoriteAuthors = new FavoriteAuthors(context);
		favoriteAuthors.load();
	}

	public void refresh() {
		dataLoadedAuthors.load();
		favoriteAuthors.clear();
		favoriteAuthors.load();
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return dataLoadedAuthors.authorsData.length;
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Object getItem(int arg0) {
		return dataLoadedAuthors.authorsData[arg0];
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AuthorHolder holder = new AuthorHolder();
		if (convertView == null || convertView.getTag() != holder) {
			convertView = mInflater.inflate(R.layout.adt_loaded_authors, null);
			holder.favorite = (ImageView) convertView.findViewById(R.id.AdtLoadedAuthorsFavorite);
			holder.text = (TextView) convertView.findViewById(R.id.AdtLoadedAuthorsText);
			holder.count = (TextView) convertView.findViewById(R.id.AdtLoadedAuthorsCount);
			convertView.setTag(holder);
		} else {
			holder = (AuthorHolder) convertView.getTag();
		}
		holder.text.setText(dataLoadedAuthors.authorsData[position].author);
		holder.count.setText("" + dataLoadedAuthors.authorsData[position].booksPath.length);
		if (favoriteAuthors.isFavorite(dataLoadedAuthors.authorsData[position].author)) {
			holder.favorite.setVisibility(View.VISIBLE);
		}
		return convertView;
	}

	class AuthorHolder {
		ImageView	favorite;
		TextView		text;
		TextView		count;
	}

}
